//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.WindowsPhoneChat.Controllers
{
    using System;
    using System.Windows;
    using System.Windows.Navigation;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.ViewModels;

    public class NavigationEvent
    {
        private const string ViewModelSuffix = "ViewModel";

        private readonly ViewModel viewModel;
        private readonly Uri uri;

        public NavigationEvent(ViewModel viewModel)
            : this(viewModel, null)
        {
        }

        public NavigationEvent(ViewModel viewModel, Uri uri)
        {
            if (viewModel == null)
            {
                throw new ArgumentNullException("viewModel");
            }

            this.viewModel = viewModel;

            if (uri == null)
            {
                uri = CreateDefaultViewUri(viewModel);
            }

            this.uri = uri;
        }

        public ViewModel ViewModel
        {
            get { return this.viewModel; }
        }

        public Uri Uri
        {
            get { return this.uri; }
        }

        public void BeginNavigate()
        {
            var rootFrame = ((App)App.Current).RootFrame;
            if (rootFrame == null)
            {
                return;
            }

            rootFrame.Navigated += this.OnNavigateCompleted;
            rootFrame.Navigate(this.Uri);
        }

        private static Uri CreateDefaultViewUri(ViewModel viewModel)
        {
            var viewName = viewModel.GetType().Name;
            if (viewName.EndsWith(ViewModelSuffix))
            {
                viewName = viewName.Substring(0, viewName.Length - ViewModelSuffix.Length);
            }

            return new Uri("/" + viewName + ".xaml", UriKind.Relative);
        }

        private void OnNavigateCompleted(object sender, NavigationEventArgs e)
        {
            ((NavigationService)sender).Navigated -= this.OnNavigateCompleted;

            var target = e.Content as FrameworkElement;
            if (target != null)
            {
                target.DataContext = this.ViewModel;
            }
        }
    }
}
